package com.imooc.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author 顾志杰
 * @date 2020/9/18-9:34
 */
@Component("authFilter")
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String AUTH = "Authorization";

    private static final String LOGINURL = "passport";


    private static final String LOGOUTURL = "/logout";

    /**
     * 对称密钥 生产环境不能这么用
     */
    private static final String KEY = "changeIt";

    private static final String ISSUER = "yao";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if(path.contains(LOGINURL)){
            if(!path.contains(LOGINURL + LOGOUTURL)){
                return chain.filter(exchange.mutate()
                        .request(request)
                        .response(response)
                        .build());
            }
        }
        HttpHeaders header = request.getHeaders();
        String token = header.getFirst(AUTH);
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();

            verifier.verify(token);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

        return chain.filter(exchange.mutate()
                .request(request)
                .response(response)
                .build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
